import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test01 {
    public int totalFruit(int[] fruits) {
        Map<Integer,Integer> hash = new HashMap<>();
        int left = 0, right = 0, num = 0;
        while(right < fruits.length){
            hash.put(fruits[right],hash.getOrDefault(fruits[right],0) + 1);
            while(hash.size() > 2){
                hash.put(fruits[left],hash.get(fruits[left]) - 1);
                if(hash.get(fruits[left]) == 0){
                    hash.remove(fruits[left]);
                }
                left++;
            }
            num = Math.max(num,right - left + 1);
            right++;
        }
        return num;
    }

    public int totalFruit2(int[] fruits) {
        //Map<Integer,Integer> hash = new HashMap<>();
        int[] hash = new int[fruits.length + 1];
        int left = 0, right = 0, num = 0;
        int kinds=  0;
        while(right < fruits.length){
            //hash.put(fruits[right],hash.getOrDefault(fruits[right],0) + 1);
            if(hash[fruits[right]] == 0) kinds++;
            hash[fruits[right]]++;
            while(kinds > 2){
                //hash.put(fruits[left],hash.get(fruits[left]) - 1);
                hash[fruits[left]]--;
                if(hash[fruits[left]] == 0){
                    kinds--;
                }
                left++;
            }
            num = Math.max(num,right - left + 1);
            right++;
        }
        return num;
    }
}
